
 /**
   * This Class Shows User Information and Reservations
   * @author Moustafa Chouraiki <mrsafu@gmail.com>
   * 
  */
package com.google.code.gestion_de_conferences;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.text.Html;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TableRow.LayoutParams;

public class UserInfoActivity extends Activity {
        
    int selectedUserId;
    AABDatabaseManager db;
    User user = new User();
    TextView reg_user_fullname,  reg_user_phone ,reg_user_username ,reg_user_company;
        
    TableLayout user_reservation_table;
    Button change_date;
    
    private final DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
    private Date selectedDate;
    private int year;
    private int month;
    private int day;
    static final int DATE_DIALOG_ID = 999;
    String currentUserId = 0+"";
        
    @Override
    public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.user_info);
	        
	    //This is to get the position of the selected item from the usersList if we chose to edit the user
	    Intent i = getIntent(); 
	   
	    //-1 is the default value of position. This value will specify that no user was selected
	    selectedUserId = i.getIntExtra("selectedUserId", -1);    
	    //Toast.makeText(this, "User: "+selectedUserId, Toast.LENGTH_LONG).show();
	    // Test if User Selected was not valid
	    if (selectedUserId != -1)
	    {       
	        db = new AABDatabaseManager(this);
	     
	        //get the selected user data
	        
	        String fullName = db.getValueByParam(0,1,"User",selectedUserId+"");
	        String phone = db.getValueByParam(0,4,"User",selectedUserId+"");
	        String username = db.getValueByParam(0,2,"User",selectedUserId+"");
	        String company = db.getValueByParam(0,3,"User",selectedUserId+"");

	        //get the current room id
	        currentUserId = selectedUserId+"";
	        
	        reg_user_fullname = (TextView) findViewById(R.id.reg_user_fullname);
	        reg_user_phone = (TextView) findViewById(R.id.reg_user_phone);
	        reg_user_username = (TextView) findViewById(R.id.reg_user_username);
	        reg_user_company = (TextView) findViewById(R.id.reg_user_company);
	        
	        user_reservation_table = (TableLayout) findViewById(R.id.user_reservation_table);
	        
	        change_date = (Button)findViewById(R.id.btn_change_date);
	        
	        reg_user_fullname.setText(Html.fromHtml("<b>"+getString(R.string.full_namei)+"</b>")+" : "+fullName); 
	        reg_user_phone.setText(Html.fromHtml("<b>"+getString(R.string.phonei)+"</b>")+" : "+phone); 
	        reg_user_username.setText(Html.fromHtml("<b>"+getString(R.string.usernamei)+"</b>")+" : "+username); 
	        reg_user_company.setText(Html.fromHtml("<b>"+getString(R.string.company)+"</b>")+" : "+company); 
	        
	        //SHow the date picker 
	        change_date.setOnClickListener(new OnClickListener() {
	
	                @SuppressWarnings("deprecation")
	                @Override
	                public void onClick(View v) {
	                        showDialog(DATE_DIALOG_ID);
	                }
	
	        });
	        	        
	        //Set the current date for the date picker button
	        setCurrentDateOnView();
	        
	        displayReservations();
	    }
        
        
    }

    /**
     * creates the table header
     * 
     *  @author Moustafa Chouraiki <mrsafu@gmail.com>
     */
    
    public TableRow getTableHeader()
    {
        //Create a table row header
        
        TableRow tr_head = new TableRow(this);
        tr_head.setId(10);
        tr_head.setBackgroundColor(Color.rgb(240, 122, 35));
        tr_head.setLayoutParams(new LayoutParams(
        LayoutParams.FILL_PARENT,
        LayoutParams.WRAP_CONTENT));        
        
        //Create a text view to hold the user name
        
        TextView label_user = new TextView(this);
        label_user.setId(21);// define id that must be unique
        label_user.setText("Room"); // set the text for the header 
        label_user.setTextColor(Color.WHITE); // set the color
        label_user.setPadding(5, 5, 5, 5); // set the padding (if required)
        tr_head.addView(label_user); // add the column to the table row here
        
        //Create a text view to hold the reservation from time
        
        TextView label_from_time = new TextView(this);
        label_from_time.setId(22);// define id that must be unique
        label_from_time.setText("From"); // set the text for the header 
        label_from_time.setTextColor(Color.WHITE); // set the color
        label_from_time.setPadding(5, 5, 5, 5); // set the padding (if required)
        tr_head.addView(label_from_time); // add the column to the table row here
        
        //Create a text view to hold the reservation from time        
        TextView label_to_time = new TextView(this);
        label_to_time.setId(23);// define id that must be unique
        label_to_time.setText("To"); // set the text for the header 
        label_to_time.setTextColor(Color.WHITE); // set the color
        label_to_time.setPadding(5, 5, 5, 5); // set the padding (if required)
        tr_head.addView(label_to_time); // add the column to the table row here
        
       return tr_head;
    } 
    
    /**
     * Creates a table row
     * 
     *  @author Moustafa Chouraiki <mrsafu@gmail.com>
     */
    
    public TableRow getTableRow(int count,String roomName,String from,String to)
    {
        
        // Create the table row
        TableRow tr = new TableRow(this);
        if(count%2!=0) tr.setBackgroundColor(Color.rgb(240, 122, 35));
        tr.setId(100+count);
        tr.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
        
        //Create a text view to hold the user name
        
        TextView room = new TextView(this);
        room.setId(count);
        room.setText(roomName); 
        room.setTextColor(Color.BLACK); 
        room.setPadding(2, 0, 5, 0); 
        tr.addView(room);
        
        //Create a text view to hold the reservation from time
        
        TextView from_time = new TextView(this);
        from_time.setId(200+count);
        from_time.setText(from); 
        from_time.setTextColor(Color.BLACK); 
        
        tr.addView(from_time); 
        
        //Create a text view to hold the reservation from time
        
        TextView to_time = new TextView(this);
        to_time.setId(200+count);
        to_time.setText(to); 
        to_time.setTextColor(Color.BLACK); 
       
        tr.addView(to_time); 
        
       return tr;
    }
            
	/**
	 * Set Date picker to current day
	 * @author Moustafa Chouraiki <mrsafu@gmail.com>
	 * 
	 */
	public void setCurrentDateOnView()
	{
	    Button reg_display_date = (Button) findViewById(R.id.btn_change_date);
	
	    final Calendar c = Calendar.getInstance();
	     year = c.get(Calendar.YEAR);
	     month = c.get(Calendar.MONTH);
	     day = c.get(Calendar.DAY_OF_MONTH);
	    
	    // set current date into textview
	    reg_display_date.setText(new StringBuilder().append(month + 1).append("/").append(day).append("/").append(year));
	            
	    try 
	    {
	            //transform to date since we need to handle it as a dates
	            selectedDate = dateFormat.parse(reg_display_date.getText().toString());
	    } 
	    catch (ParseException e) {
	            
	            e.printStackTrace();
	    }                
	        
	}
        

    /**
     * Create date picker dialog
     * 
     * @author Moustafa Chouraiki <mrsafu@gmail.com>
     * 
     */
    @Override
    protected Dialog onCreateDialog(int id)
    {
        switch (id) {
                case DATE_DIALOG_ID:
                        // set date picker as current date
                        return new DatePickerDialog(this, datePickerListener, year, month,day);
        }

        return null;
    }

    /**
     * Setting the date picker
     * 
     * @author Moustafa Chouraiki <mrsafu@gmail.com> 
     * 
     */
    private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() 
    {
        // when dialog box is closed, below method will be called.
        public void onDateSet(DatePicker view, int selectedYear,int selectedMonth, int selectedDay) 
        {
            year = selectedYear;
            month = selectedMonth;
            day = selectedDay;
            // set selected date into textview
            change_date.setText(new StringBuilder().append(month + 1).append("/").append(day).append("/").append(year));
            try 
            {
                    selectedDate = dateFormat.parse(change_date.getText().toString());
            }
            catch (ParseException e) 
            {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
            }                    
        }
    };
    
    /**
     * Prints all reservations of a selected date for the selected room
     * @author Moustafa Chouraiki <mrsafu@gmail.com> 
     * 
     * 
     */     
    private void displayReservations()
    {
                
        ArrayList<ArrayList<Object>> dataArrays = new ArrayList<ArrayList<Object>>();
        
        //get the reservations for the selected date
        dataArrays = db.getRowAsArrayByPosition(1,"Reservation",selectedDate.toString());
    
        if(dataArrays.size()<1)
        {
                 TextView no_reservations = new TextView(this);
                 no_reservations.setText("No reseravtion for "+selectedDate);
        }
        else
        {               
            //get the table header
            TableRow tr_head = getTableHeader();
            
            //add table header to the table layout
            user_reservation_table.addView(tr_head, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
            
            for (int position=0; position < dataArrays.size(); position++)
            { 
                ArrayList<Object> row = dataArrays.get(position);
                
                //room id of the reservation
                String userId = row.get(5).toString();
        
                if(userId.equals(currentUserId))
                {
                    //get the full name of the user that has the reservation
                    String roomName = db.getValueByParam(0,1,"Room",row.get(4).toString());
                    
                    String from = row.get(2).toString();
                    String to = row.get(3).toString();
                    
                    TableRow tr = getTableRow (position,roomName,from,to);
                    
                    // finally add this to the table row
                    user_reservation_table.addView(tr, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));    
                                        
                }
            } 
        }        
    }
	/**
	   * This function create the menu in the user info activity
	   * @author Moustafa Chouraiki <mrsafu@gmail.com>
	   * @param menu
	   */
     @Override
     public boolean onCreateOptionsMenu(Menu menu) {
         MenuInflater inflater = getMenuInflater();
         inflater.inflate(R.menu.menu, menu);              
         return true;
     }
     
     /**
       * This function handles clicking any of the menu's items
       * @author Rayan Zahab <differentruna@gmail.com> 
       * @author Hyame Alameddine <hyame.alameddine@gmail.com>
       * @param menu
       */
     @Override
     public boolean onOptionsItemSelected(MenuItem item) 
      {       
          Intent i;
          
          switch (item.getItemId()) 
          {
           
          case R.id.users:     
                i = new Intent(getApplicationContext(), UsersListActivity.class);
                startActivity(i);
                break;
          case R.id.reservations:     
                i = new Intent(getApplicationContext(), ReservationsListActivity.class);
                startActivity(i);
                break;
          case R.id.conferences:     
                i = new Intent(getApplicationContext(), RoomsListActivity.class);
                startActivity(i);
                break;
          case R.id.edit_profile:                         
                i = new Intent(getApplicationContext(), RegisterActivity.class);
                i.putExtra("editAdmin", 1);
                startActivity(i);
                break;
          case R.id.logout: 
                i = new Intent(getApplicationContext(), LoginActivity.class);
                startActivity(i);
                break;
          case R.id.help:     
                AlertDialog alertDialog = new AlertDialog.Builder(this).create();
                alertDialog.setTitle("Help!");
                alertDialog.setMessage("Gestion de conference is an application helps you manage reservations, add rooms ,add users and reserve rooms to organize conferences !");
                alertDialog.setIcon(R.drawable.icon);
                alertDialog.show();
                break;
          case R.id.developers: 
                Toast.makeText(this, "Rayan,Hyame,Mostafa!", Toast.LENGTH_LONG).show();
                break;
            
        }
        return true;
    }
}